package com.seguriapp.paperworks.gwt.client.activity;

import java.util.List;

import net.customware.gwt.dispatch.client.DispatchAsync;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.seguriapp.common.gwt.client.AbstractSeguriAppActivity;
import com.seguriapp.common.gwt.client.AbstractSeguriAppPlace;
import com.seguriapp.common.gwt.client.SeguriAppCallback;
import com.seguriapp.common.gwt.client.SeguriAppClientSession;
import com.seguriapp.common.gwt.client.SeguriAppDisplay;
import com.seguriapp.entities.Paperwork;
import com.seguriapp.paperworks.gwt.shared.GetPaperworksListAction;
import com.seguriapp.paperworks.gwt.shared.GetPaperworksListResult;

public class PaperworksListActivity extends AbstractSeguriAppActivity {

  private List<Paperwork> paperworksList;
  private final Display display;

  public PaperworksListActivity(final DispatchAsync dispatchAsync, final EventBus eventBus, final PlaceController placeController,
      final Display display, final AbstractSeguriAppPlace place, final SeguriAppClientSession clientSession) {
    super(dispatchAsync, eventBus, placeController, place, clientSession);
    display.setPresenter(this);
    this.display = display;
  }

  @Override
  protected void onStart(final AcceptsOneWidget widget, final EventBus eventBus) {
    widget.setWidget(display.asWidget());
    initializePaperworksList();
  }

  public void updatePaperworkData(final Long paperworkId) {
    for (final Paperwork paperwork : paperworksList) {
      if (paperwork.getId().equals(paperworkId)) {
        display.showPaperworkData(paperwork);
        break;
      }
    }
  }

  private void initializePaperworksList() {
    dispatchAsync.execute(new GetPaperworksListAction(), new SeguriAppCallback<GetPaperworksListResult>() {

      public void onSuccess(final GetPaperworksListResult result) {
        paperworksList = result.getPaperworksList();
        display.initializePaperworkList(paperworksList);
      }

      public void onFailure(Throwable e) {
        display.initializePaperworkList(null);
      }
    });
  }

  public interface Display extends SeguriAppDisplay {

    void setPresenter(PaperworksListActivity presenter);

    void showPaperworkData(Paperwork paperwork);

    void initializePaperworkList(List<Paperwork> paperworksList);

  }

}
